package com.zxq.ai.domain.user.account;

import com.zxq.common.utils.DateUtil;
import com.zxq.ai.domain.AggregateRoot;
import com.zxq.ai.domain.exception.CashAccountWithdrawException;
import lombok.*;

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class CashAccount implements AggregateRoot<Long> {

    private Long accountId;  // account属于某个user，所以 userId 即是 accountId
    private Long userId;

    private Long balanceAmount;         // 账户余额 balanceAmount = frozenAmount + availableAmount
    private Long frozenAmount;          // 冻结金额
    private Long availableAmount;       // 可用余额

    private Long totalRechargeAmount;   // 累计充值金额
    private Long totalWithdrawAmount;   // 累计提现金额

    private Long createAt;  // 创建时间
    private String createBy;  // 创建人 userId
    private Long updateAt;  // 更新时间
    private String updateBy;  // 更新人


    @Override
    public Long id() {
        return accountId;
    }

    /**
     * 【现金】充值
     * @param amount 操作金额
     * @param operator 操作人
     */
    public void recharge(Long amount, String operator) {
        balanceAmount += amount;
        availableAmount += amount;
        totalRechargeAmount += amount;
        updateBy = operator;
        updateAt = DateUtil.millis();
    }

    /**
     * 【现金】提现
     * @param amount 操作金额
     * @param operator 操作人
     */
    public void withdraw(Long amount, String operator) {
        if (amount > availableAmount) {
            throw new CashAccountWithdrawException(String.format("提现金额[%s]不能大于可用余额[%s]", amount, availableAmount));
        }
        if (amount > balanceAmount) {
            throw new CashAccountWithdrawException(String.format("提现金额[%s]不能大于账户余额[%s]", amount, balanceAmount));
        }
        balanceAmount -= amount;
        availableAmount -= amount;
        totalWithdrawAmount += amount;
        updateBy = operator;
        updateAt = DateUtil.millis();
    }


}